class UsersController < ApplicationController
  before_action :signed_in_user, only: [:edit, :update, :index]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  respond_to :html
  def new
    @user = User.new()
  end

  def show
    @user=User.find(params[:id])
    @microposts = @user.microposts.paginate(page: params[:page])
  end
  def edit

  end

  def search
  end

  def create

    @user = User.new(user_params)    # Not the final implementation!
    if @user.save
      sign_in @user
      flash[:success] = "欢迎您,#{@user.name}"
      redirect_to @user
    else
      render 'new'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "用户已删除."
    #respond_with(@user,:location=>:back)
     redirect_to :back  #users_url
  end

  def set_admin

    #render 'shared/debug_page_params'

    User.find(params[:id]).toggle!(:admin)

    redirect_to users_url
  end


  def index
    @users = User.where(["name like ?", "%#{params[:search]}%"] ).paginate(page: params[:page])
  end
  def update



    if @user.update_attributes(user_params)
      flash[:success] = "资料已更新"
      redirect_to @user
    else
      render 'edit'
    end
  end



  private

  def user_params
    params.require(:user).permit(:name,:email, :password,
                                 :password_confirmation)
  end



  def correct_user
    @user = User.find(params[:id])
    redirect_to(root_path) unless current_user?(@user)
  end

  def admin_user
    redirect_to(root_path) unless current_user.admin?
  end
end
